package com.example.autopia.view.Activities

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.autopia.databinding.ActivityAddNewsBinding
import com.example.autopia.model.Item.News
import com.example.autopia.model.Repositories.NewsRepository
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.utilities.ImageManager
import com.example.autopia.utilities.TimeManager
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase

class AddNewsActivity : AppCompatActivity() {

    private lateinit var binding: ActivityAddNewsBinding
    private val timeManager = TimeManager()
    private val imageManager = ImageManager()
    private val newsRepository = NewsRepository()
    private val userRepository = UsersRepository()
    private val PICK_IMAGE_REQUEST = 1
    private var photo : String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAddNewsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btBack.setOnClickListener {
            finish()
        }
        binding.btAdd.setOnClickListener {
            addNews()
        }
        binding.btAddPhoto.setOnClickListener {
            addPhoto()
        }
    }

    private fun addNews() {
        val firebaseAuth = Firebase.auth
        if (binding.tvTitle.text.toString().isNotEmpty() && binding.tvMainText.text.toString()
                .isNotEmpty()
        ) {
            val user = userRepository.getUserById(firebaseAuth.currentUser?.uid ?: "")

            var viewType = 1
            if (photo!=null) {
                viewType = 2
            }else{
                photo="1"
            }

            user.observe(this) { user ->
                val newNews = News(
                    "1",
                    user.photo,
                    user.name,
                    0,
                    null,
                    binding.tvTitle.text.toString(),
                    binding.tvMainText.text.toString(),
                    viewType,
                    photo!!,
                    timeManager.getCurrentUnixTime(),
                    user.id,
                    user.verificated
                )
                newsRepository.addNews(newNews)
                Toast.makeText(
                    this@AddNewsActivity,
                    "Ваше обсуждение опубликовано",
                    Toast.LENGTH_SHORT
                ).show()
                finish()
            }
        } else {
            if (binding.tvMainText.text.toString().isEmpty()) {
                Toast.makeText(
                    this@AddNewsActivity,
                    "Введите основной текст обсуждения",
                    Toast.LENGTH_SHORT
                ).show()
            }
            if (binding.tvTitle.text.toString().isEmpty()) {
                Toast.makeText(
                    this@AddNewsActivity,
                    "Введите заголовок обсуждения",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    fun addPhoto(){
        // Вызываем интент для выбора изображения из галереи
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, PICK_IMAGE_REQUEST)
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                val imageUri = data.data
                photo = imageUri?.let { imageManager.imageToByteArray(it,contentResolver) }
                if (photo!=null){
                    binding.file.visibility = View.VISIBLE
                    binding.tvFileName.text = imageManager.getFileNameWithExtension(imageUri.toString())
                    binding.btClose.setOnClickListener {
                        photo = null
                        binding.file.visibility = View.GONE
                    }
                }else{
                    Toast.makeText(
                        this@AddNewsActivity,
                        "Размер фотографии превышает 2мб",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }
}